<template>
  <div style="border: 1px solid #dcdcdc" class="basic-editor">
    <Toolbar
      style="border-bottom: 1px solid #dcdcdc"
      :editor="editorRef"
      :default-config="toolbarConfig"
    />
    <Editor
      :model-value="modelValue"
      class="flex-1 overflow-y-hidden"
      :default-config="editorConfig"
      @on-created="handleCreated"
      @update:model-value="handleContentChange"
    />
  </div>
</template>

<script setup lang="ts">
// 引入 css
import '@wangeditor/editor/dist/css/style.css'

import type { IDomEditor, IToolbarConfig } from '@wangeditor/editor'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
interface IProps {
  modelValue: string
  height?: string
  mode?: 'html' | 'text'
}

interface IEmit {
  (event: 'update:model-value', value: string): void
}
withDefaults(defineProps<IProps>(), {
  modelValue: '',
  mode: 'html',
  height: '500px'
})

const emit = defineEmits<IEmit>()

type EditorInstance = IDomEditor

// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef<EditorInstance>()

const handleCreated = (editor: EditorInstance) => {
  // 记录 editor 实例，重要！
  editorRef.value = editor
}

// [ "bold","underline","italic","through","code","sub","sup","clearStyle","color","bgColor","fontSize","fontFamily","indent","delIndent",
// "justifyLeft","justifyRight","justifyCenter","justifyJustify","lineHeight","insertImage","deleteImage","editImage","viewImageLink",
// "imageWidth30","imageWidth50","imageWidth100","divider","emotion","insertLink","editLink","unLink","viewLink","codeBlock","blockquote",
// "headerSelect","header1","header2","header3","header4","header5","todo","redo","undo","fullScreen","enter","bulletedList","numberedList",
// "insertTable","deleteTable","insertTableRow","deleteTableRow","insertTableCol","deleteTableCol","tableHeader","tableFullWidth",
// "insertVideo","uploadVideo","editVideoSize","uploadImage","codeSelectLang"]

const toolbarConfig: Partial<IToolbarConfig> = {
  toolbarKeys: [
    'headerSelect',
    'bold',
    'fontSize',
    'italic',
    'underline',
    'through',
    'justifyLeft',
    'justifyCenter',
    'justifyRight',
    'bulletedList',
    'todo',
    'numberedList',
    'blockquote',
    'emotion'
  ]
}
const editorConfig = { placeholder: '请输入内容...' }

const handleContentChange = (value: string) => {
  emit('update:model-value', value)
}
// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
  const editor = editorRef.value
  if (editor == null) return
  editor.destroy()
})

const getText = () => {
  const editor = editorRef.value
  if (editor == null) return ''
  return editor.getText()
}

defineExpose({
  getText
})
</script>

<style scoped lang="scss">
.basic-editor {
  @apply h-full flex flex-col;
}
</style>
